package net.larsan.dconf.util;

import static net.larsan.dconf.util.DPaths.safeParse;
import static org.apache.commons.lang.Validate.notNull;

import java.util.Properties;

import net.larsan.dconf.DNode;
import net.larsan.dconf.DNodeStore;
import net.larsan.dconf.DPath;

/**
 * This helper class is able to import a properties set
 * at a given root node. 
 * 
 * @author Lars J. Nilsson
 */
public class PropertiesImporter {

	private final DNode target;
	private final boolean owerwrite;

	/**
	 * @param target Node to use as root for the import, must not be null
	 * @param owerwrite True to overwrite any existing attributes, false otherwise
	 */
	public PropertiesImporter(DNode target, boolean owerwrite) {
		notNull(target);
		this.owerwrite = owerwrite;
		this.target = target;
	}
	
	/**
	 * @return The target node, never null
	 */
	public DNode getTarget() {
		return target;
	}
	
	/**
	 * @param props Properties to import, must not be null
	 */
	public void performImport(Properties props) {
		DNodeStore store = target.getStore();
		// pre-create the domain prefix
		String domain = target.getPath().getDomain() + ":/";
		for (Object o : props.keySet()) {
			String key = o.toString();
			// get last '.' which delimits attribute from node path
			int index = key.lastIndexOf('.');
			if(index == -1) {
				// direct attribute on root
				target.setAttribute(key, props.getProperty(key));
			} else {
				// get attribute name
				String attribute = key.substring(index + 1);
				// get node path by replacing '.' for '/'
				String nodePath = key.substring(0, index).replace('.', '/');
				// is this really "safe" ?
				DPath path = safeParse(domain + nodePath);
				DNode child = store.get(path, true);
				if(owerwrite || !child.hasAttribute(attribute)) {
					// if it doesn't exist or we're overwriting
					child.setAttribute(attribute, props.getProperty(key));
				}
			}
		}
	}
}
